<?php

class Auth_Acl_Storage_Config extends Auth_Acl_Storage_Abstract {

	protected $_cacheIdentify = __CLASS__;

	private function _checkIfOneRule($configSection) {
		if ((count($configSection->toArray()) != 0) && (
		!(boolean)$configSection->get('role') &&
		!(boolean)$configSection->get('resource') &&
		!(boolean)$configSection->get('privileges')
		)) {
			return false;
		} else return true;
	}

	protected function _gen() {
		$result = new Zend_Acl;

		$context = Zend_Registry::isRegistered('context') ? Zend_Registry::get('context') : 'production';
		$config =  new Zend_Config_Xml( dirname(__FILE__).'/../../../../conf/appconf.xml',$context);

		// публичная роль - родитель всех ролей
		$result->addRole(new Zend_Acl_Role('user'));


		if ($aclConfig = $config->get('acl')) {

			if ($rulesConfig = $aclConfig->get('rule')) {

				if ($this->_checkIfOneRule($aclConfig->get('rule'))) {
					$this->_allowAccess($result,$rulesConfig);
				} else {
					foreach ($rulesConfig as $ruleConfig) {
						$this->_allowAccess($result,$ruleConfig);
						

					}
				}
			}
		}

		return $result;
	}

	private function _allowAccess(Zend_Acl &$result,$ruleConfig) {
		$role = null;
		if ($ruleConfig->get('role')) {

			if (!$result->hasRole($ruleConfig->role)) {
				$result->addRole(new Zend_Acl_Role($ruleConfig->role),'user');
			}

			$role = (string)$ruleConfig->role;
		}

		$resource = null;
		if ($ruleConfig->get('resource')) {
			if (!$result->has($ruleConfig->resource))
				$result->add(new Zend_Acl_Resource($ruleConfig->resource));

			$resource = (string)$ruleConfig->resource;
		}

		$privilege = null;
		if ($ruleConfig->get('privilege')) {
			$privilege = $ruleConfig->privilege;
		}

		$result->allow($role,$resource,$privilege);

		return $result;
	}
}